package net.zjitc.security;

import cn.hutool.json.JSONUtil;
import net.zjitc.common.ResponseResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 毛钰深
 * @create 2022/1/25
 * 权限不足处理器
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //设置响应头
        httpServletResponse.setContentType("application/json;charset-UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //获取response的输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        ResponseResult res=new ResponseResult();

        res.setForbidden(e.getMessage());
        //使用工具类将res的数据写到输出流中并返回
        outputStream.write(JSONUtil.toJsonStr(res).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
